/*
 *    Copyright (c) 2018-2025, ddc All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: ddc
 */

package cn.ddiancan.xddcloud.sentinel.handle;

import cn.ddiancan.xddcloud.common.entity.CommonResult;
import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

/**
 * 降级 限流策略
 */
@Slf4j
public class XddcloudRequestBlockHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s,
        BlockException e) throws Exception {
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
        CommonResult<String> commonResult = new CommonResult<>();
        commonResult.setCode(HttpStatus.TOO_MANY_REQUESTS.value());
        commonResult.setMsg("too many request");
        commonResult.setData(s);
        httpServletResponse.getWriter().print(JSON.toJSONString(commonResult));
    }
}
